package com.haieros.www.purerunshowsystem.activity;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.haieros.www.purerunshowsystem.BaseAcivity;
import com.haieros.www.purerunshowsystem.R;
import com.haieros.www.purerunshowsystem.utils.DateJudgeUtil;
import com.haieros.www.purerunshowsystem.utils.SharedPreferencesUtils;
import com.haieros.www.purerunshowsystem.utils.SoundPoolUtils;

import org.greenrobot.eventbus.EventBus;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017\12\20 0020.
 */

public class LaunchEquipmenActivity extends AppCompatActivity {
    private String stateMessage = "即将开启臭氧设备，请仓内人员尽快离开";
    private long minute = 1;//这是分钟
    private long second = 0;//这是分钟后面的秒数。这里是以30分钟为例的，所以，minute是30，second是0
    private TextView timeView, timeViewState;
    private Timer timer;
    private TimerTask timerTask;
    int flag = 0;
    int current;
    AudioManager am;
    Date date, settingDate;
    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    private int playSoundFlag = 1;
    //页面异常销毁标记
    private final boolean EXCEPTION_PAUSE_FLAG = true;
    private boolean isSilentModeFlag = false;
    //这是接收回来处理的消息
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (minute == 0) {
                if (second == 0) {

                    flag++;
                    if (flag == 3) {
                        Log.e("------", "flag==" + flag + "销毁页面");
                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                        }
                        if (timerTask != null) {
                            timerTask = null;
                        }
                        finish();
                    } else {
                        if (flag == 1) {
                            Log.e("------", "flag==" + flag);
                            SoundPoolUtils.getInstence(getApplicationContext()).startSound2(SoundPoolUtils.POP_UP, 1);
                            timeViewState.setText("臭氧设备开启中，请勿进入");
                        }
                        if (flag == 2) {
                            Log.e("------", "flag==" + flag);
                            SoundPoolUtils.getInstence(getApplicationContext()).startSound2(SoundPoolUtils.CLICK_RESPONSE, 2);
                            timeViewState.setText("空气净化中请勿进入");
                        }
                        //timeView.setText("Time out !");
                        minute = 1;
                    }

                } else {
                    second--;
                    if (second >= 10) {
                        timeView.setText("0" + minute + ":" + second);
                    } else {
                        timeView.setText("0" + minute + ":0" + second);
                    }
                }
            } else {
                if (second == 0) {
                    second = 59;
                    minute--;
                    if (minute >= 10) {
                        timeView.setText(minute + ":" + second);
                    } else {
                        timeView.setText("0" + minute + ":" + second);
                    }
                } else {
                    second--;
                    if (second >= 10) {
                        if (minute >= 10) {
                            timeView.setText(minute + ":" + second);
                        } else {
                            timeView.setText("0" + minute + ":" + second);
                        }
                    } else {
                        if (minute >= 10) {
                            timeView.setText(minute + ":0" + second);
                        } else {
                            timeView.setText("0" + minute + ":0" + second);
                        }
                    }
                }
            }
        }

    };

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        return true;
//    }
//
//    @Override
//    public void onBackPressed() {
//        return;
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        Log.e("===", "onCreate()");
        setContentView(R.layout.activity_launchequipmen);
        date = new Date();
        //Toast.makeText(this,"onCreate "+(boolean)SharedPreferencesUtils.getParam(this,"pauseflag",false)+" "+DateJudgeUtil.getInstence(this).judgeTime(date),Toast.LENGTH_LONG).show();
        SoundPoolUtils.getInstence(this);
        Log.e("======", "" + DateJudgeUtil.getInstence(this).judgeTime(date));
        //    Toast.makeText(this, "onCrea pauseflag"+(boolean) SharedPreferencesUtils.getParam(this, "pauseflag", false), Toast.LENGTH_LONG).show();
        if ((boolean) SharedPreferencesUtils.getParam(this, "pauseflag", false)) {
            Toast.makeText(this, "进入", Toast.LENGTH_LONG).show();
            SharedPreferencesUtils.setParam(this, "pauseflag", false);
            try {
                switch (DateJudgeUtil.getInstence(this).judgeTime(date)) {
                    case 1:
                        settingDate = df.parse("17:25:00");
                        countTime();
                        playSoundFlag = 1;
                        Toast.makeText(this, "switch 1", Toast.LENGTH_LONG).show();
                        break;
                    case 2:
                        Toast.makeText(this, "switch 2", Toast.LENGTH_LONG).show();
                        flag = 1;
                        stateMessage = "臭氧设备开启中，请勿进入";
                        settingDate = df.parse("10:05:00");
                        playSoundFlag = 2;
                        countTime();
                        break;
                    case 3:
                        Toast.makeText(this, "switch 3", Toast.LENGTH_LONG).show();
                        flag = 2;
                        stateMessage = "空气净化中，请勿进入";
                        settingDate = df.parse("17:55:00");
                        playSoundFlag = 3;
                        countTime();
                        break;
                    case 503:
                        Toast.makeText(this, "switch 503", Toast.LENGTH_LONG).show();
                        //finish();
                        break;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else
        {
            //Toast.makeText(this, "没进入", Toast.LENGTH_LONG).show();
        }
        initView();
        setVolue();
        SoundPoolUtils.getInstence(this).startSound(playSoundFlag);
    }

    public void initView() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String date = sdf.format(new Date());
        Log.d("----", "time" + date);
        // 流媒体操作类
        timeView = (TextView) findViewById(R.id.tv_time);
        timeViewState = (TextView) findViewById(R.id.tv_equipmen_state);
        timeViewState.setText(stateMessage);
        timeView.setText(minute + ":" + second);
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
            }
        };
        timer = new Timer();
    }

    public void setVolue() {
        am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if(isSilentModeFlag=isSilentMode())
        {
            am.setStreamMute(AudioManager.STREAM_SYSTEM, false);
        }
        current = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        //am.setStreamVolume(AudioManager.STREAM_MUSIC,am.getStreamMaxVolume(AudioManager.STREAM_MUSIC),AudioManager.FLAG_SHOW_UI);
        am.setStreamVolume(AudioManager.STREAM_MUSIC, 1, AudioManager.FLAG_SHOW_UI);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (flag != 3) {
            //非正常销毁页面标记  true
            SharedPreferencesUtils.setParam(this, "pauseflag", EXCEPTION_PAUSE_FLAG);
            SharedPreferencesUtils.setParam(this, "minute", minute);
            SharedPreferencesUtils.setParam(this, "second", second);
        }
        if (flag == 3) {
            SharedPreferencesUtils.setParam(this, "pauseflag", false);
        }
    }

    /**
     * 是否静音状态
     *
     * @return true是 false否
     */
    private boolean isSilentMode() {
        return am.getRingerMode() != AudioManager.RINGER_MODE_SILENT;
    }

    @Override
    protected void onPause() {
        super.onPause();

        Log.e("===", "onPause");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e("===", "onStart");
        EventBus.getDefault().post("onCreate");
        timer.schedule(timerTask, 0, 1000);
    }

    @Override
    protected void onDestroy() {
        Log.e("===", "onDestroy");
        EventBus.getDefault().post("onDestroy");
        // am.setStreamVolume(AudioManager.STREAM_MUSIC,current,AudioManager.FLAG_SHOW_UI);
        // SoundPoolUtils.getInstence(this).destorySoundPool();
        //停止音乐
        // SoundPoolUtils.getInstence(this).stopSound(playSoundFlag);
        if(flag==3)
        {
            SoundPoolUtils.getInstence(this).destorySoundPool();
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask = null;
        }
        minute = -1;
        second = -1;
        super.onDestroy();
    }

    public void countTime() {
        try {

            Date nowDate = df.parse(df.format(date));
            long diff = settingDate.getTime() - nowDate.getTime();//这样得到的差值是豪秒级别
            minute = (int) (diff / (1000 * 60));
            second = (int) (diff % (1000 * 60) / 1000);
            Toast.makeText(this, minute + "分" + second + "秒", Toast.LENGTH_LONG).show();
            Log.e("=======", minute + "分" + second + "秒");
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }
}
